﻿using System;
using System.Collections.Generic;
using System.Text;
using DevComponents.DotNetBar;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using ZYCommon;
using TextEditor.TextDocument.Document;
using System.Data;
using System.Reflection;
using Bifrost;
using System.Xml;
using TextEditor;
using TextEditor.TextDocument.frmWindow;
using Bifrost.WcfSvr;

namespace CLIENT_EMR
{
    /// <summary>
    /// 公共函数，参数对象
    /// 
    /// </summary>
    public class ComHelp
    {
        ///// <summary>
        ///// 公共服务操作对象
        ///// </summary>
        //public static WcfSvr.Service wc = new CLIENT_EMR.WcfSvr.Service();

        ///// <summary>
        ///// 当前登录帐号用户信息
        ///// </summary>
        //public static WcfSvr.Class_Account UserAccount;

        // 快捷码查询列表         
        private static frmCodeSelect uccodeselect = new frmCodeSelect();

        /// <summary>
        /// 体温单信息读取
        /// </summary>
        public static Dictionary<string, string> dicRYText = new Dictionary<string, string>();


        /// <summary>
        /// 当前模版
        /// </summary>
        public static string CurrentTemplateContent = "";

        /// <summary>
        /// 当前操作编辑器
        /// </summary>
        public static frmText CurrentFrmText;

        //已签名参数
        public static bool MyDocStye = false;
        
        //当前病人主键
        public static InPatientInfo patientinfo;

        public static DataTable ToDataTable(DataRow[] rows)
        {
            if (rows == null || rows.Length == 0) return null;
            DataTable tmp = rows[0].Table.Clone(); // 复制DataRow的表结构
            foreach (DataRow row in rows)
            {

                tmp.ImportRow(row); // 将DataRow添加到DataTable中
            }
            return tmp;
        }
      

        /// <summary>
        /// Bitmap格式的转换
        /// </summary>
        /// <param name="ImageByte">字节流</param>
        /// <returns></returns>
        public static Bitmap ByteToImg(byte[] ImageByte)
        {
            if (ImageByte == null)
            {
                return null;
            }
            try
            {
                return new Bitmap(new MemoryStream(ImageByte));
            }
            catch
            {
                return null;
            }
        }
       
       
        public static void EMRDoc_OnDrawPageHeader(Graphics g, Rectangle drawRegion, int pageIndex, PageHeaders splitStaterHeader, ZYTextDocument emrdoc)
        {
            Font f = new Font("宋体", 12f);
            Font hospitalFont = new Font("宋体", 16);
            Font textNameFont = new Font("黑体", 20);
            StringFormat titleStringFormat = new StringFormat();
            titleStringFormat.Alignment = StringAlignment.Center;
            int titleMarginTop = emrdoc.Pages.TopMargin - emrdoc.Pages.TitleMarginTop;

            Pen p = new Pen(Color.Black);
            Brush b = new SolidBrush(Color.Black);

            if (!emrdoc.Pages.EnablePageHeader) //是否隐藏或显示页眉
            {
                g.DrawLine(p, drawRegion.Left, drawRegion.Top - 5, drawRegion.Left + drawRegion.Width, drawRegion.Top - 5);
                g.DrawString(Bifrost.App.HospitalTittle, hospitalFont, b, new Rectangle(drawRegion.Left, drawRegion.Top - (titleMarginTop + 10), drawRegion.Width, 25), titleStringFormat);
                g.DrawString(emrdoc.Us.TextName, textNameFont, b, new Rectangle(drawRegion.Left, drawRegion.Top - (titleMarginTop - 25), drawRegion.Width, 34), titleStringFormat);
            }
            if (emrdoc.PageHeader != null)
            {
                ArrayList list = new ArrayList();
                int maxWdith = 0;
                string patient_name = "姓名:" + emrdoc.PageHeader["姓名"];
                int pWidth = GetTextWidth(g, patient_name, f);
                list.Add(new PageHeaderNode(patient_name, pWidth));
                maxWdith += pWidth;

                string patient_sex = "性别:" + emrdoc.PageHeader["性别"];
                pWidth = GetTextWidth(g, patient_sex, f);
                list.Add(new PageHeaderNode(patient_sex, pWidth));
                maxWdith += pWidth;

                string patient_age = "年龄:" + emrdoc.PageHeader["年龄"];
                pWidth = GetTextWidth(g, patient_age, f);
                list.Add(new PageHeaderNode(patient_age, pWidth));
                maxWdith += pWidth;

                string bed_no = "床号:" + (splitStaterHeader.Bed_no != "" ? splitStaterHeader.Bed_no : emrdoc.PageHeader["床号"]);
                pWidth = GetTextWidth(g, bed_no, f);
                list.Add(new PageHeaderNode(bed_no, pWidth));
                maxWdith += pWidth;

                string section_name = "科室:" + (splitStaterHeader.Section_name != "" ? splitStaterHeader.Section_name : emrdoc.PageHeader["科别"]);
                pWidth = GetTextWidth(g, section_name, f);
                list.Add(new PageHeaderNode(section_name, pWidth));
                maxWdith += pWidth;

                //string area_name = "病区:" + (splitStaterHeader.Sick_area != "" ? splitStaterHeader.Sick_area : emrdoc.PageHeader["病区"]);
                //pWidth = DataInit.GetTextWidth(g, area_name, f);
                //list.Add(new PageHeaderNode(area_name, pWidth));
                //maxWdith += pWidth;


                string p_id = "病案号:" + emrdoc.PageHeader["住院号"];
                pWidth = GetTextWidth(g, p_id, f);
                list.Add(new PageHeaderNode(p_id, pWidth));
                maxWdith += pWidth;

                int MarginWidth = (drawRegion.Width - maxWdith) / (list.Count - 1);
                int realWidth = 0;

                if (!emrdoc.Pages.EnablePageHeader) //是否隐藏或显示页眉
                {
                    foreach (PageHeaderNode node in list)
                    {
                        g.DrawString(node.HeaderStr, f, b, drawRegion.Left + realWidth, drawRegion.Top - 26, System.Drawing.StringFormat.GenericTypographic);
                        realWidth += node.Width + MarginWidth;
                    }
                }

                Font bottomPageCurrent = new Font("宋体", 10.5f);
                if (!emrdoc.Pages.EnablePageFooter) //是否隐藏或显示页脚
                {
                    g.DrawLine(p, drawRegion.Left, drawRegion.Bottom, drawRegion.Left + drawRegion.Width, drawRegion.Bottom);
                    g.DrawString("第  " + (pageIndex + emrdoc.PageStartIndex) + "  页", bottomPageCurrent, b, new Rectangle(drawRegion.Left, drawRegion.Bottom + 5, drawRegion.Width, 20), titleStringFormat);
                }
                bottomPageCurrent.Dispose();
            }
            p.Dispose();
            b.Dispose();
            f.Dispose();
            hospitalFont.Dispose();
            textNameFont.Dispose();
        }


        /// <summary>
        /// 保存文书
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void saveDocument(object sender, EventArgs e)
        {
            try
            {                
                if (CurrentFrmText != null)
                {
                    if (CurrentFrmText.MyDoc.Us.TextKind_id == 0 || CurrentFrmText.MyDoc.Locked)
                    {
                        App.Msg("文书已经锁定！");
                        return;
                    }
                    string str = "";
                    if (CurrentFrmText.MyDoc.Us.TextKind_id == 127)//上级查房记录提交之前提醒
                    {
                        str = @"请确认检查结果(异常)分析、目前诊断、诊断依据、鉴别诊断、下一步诊疗计划，预后及新进展（主任查房必写）是否书写完整!";

                    }
                    else if (CurrentFrmText.MyDoc.Us.TextKind_id == 120 ||
                        CurrentFrmText.MyDoc.Us.TextKind_id == 121 ||
                        CurrentFrmText.MyDoc.Us.TextKind_id == 47553087 ||
                        CurrentFrmText.MyDoc.Us.TextKind_id == 47553088 ||
                        CurrentFrmText.MyDoc.Us.TextKind_id == 47553089 ||
                        CurrentFrmText.MyDoc.Us.TextKind_id == 6982569)//入院记录提交之前提醒
                    {
                        str = "请确认主诉、现病史与诊断是否相符合!";
                    }


                    if (!string.IsNullOrEmpty(str))
                    {
                        if (!App.Ask(str))
                        {
                            return;
                        }
                    }
                    //提交按钮操作 true 暂存false
                    string btnName = "";
                    bool blfalse = false;
                    if (sender is ButtonItem)
                    {
                        btnName = (sender as ButtonItem).Name;                    
                    }
                    else if (sender is ButtonX)
                    {                     
                        btnName = (sender as ButtonX).Name;
                    }
                    if (btnName == "btnCommit")
                        blfalse = true;

                    #region 性别关键字检查
                    if (blfalse)
                    {
                        StringBuilder filterMessage;
                        string first;
                        CurrentFrmText.MyDoc.FindWords(out filterMessage, out first);
                        if (filterMessage.Length > 0)
                        {
                            filterMessage.Insert(0, "该病人性别为【" + (CurrentFrmText.MyDoc.Us.InpatientInfo.Gender_Code == "0" ? "男" : "女") + "】文书中含有下列关键字,继续保存点是,不保存点否\n");
                            if (MessageBox.Show(filterMessage.ToString(), "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No)
                            {
                                CurrentFrmText.MyDoc._Find(first, 0);
                                return;
                            }
                        }
                    }

                    #endregion

                    /***
                     * 验证元素
                     */
                    if (blfalse && !CurrentFrmText.MyDoc.CheckContent())
                    {
                        return;
                    }

                    if (!MyDocStye)
                    {
                        if (blfalse && CurrentFrmText.MyDoc.Us.TextKind_id != 1724 && CurrentFrmText.MyDoc.Us.TextKind_id != 133)
                        {//会诊申请不进入
                            if (!CurrentFrmText.MyDoc.SaveTrue)
                            {
                                //CurrentFrmText.MyDoc.isHaveTextId()
                                if (CurrentFrmText.MyDoc.isHaveTextId())
                                {
                                    if (!CurrentFrmText.MyDoc._InsertSignature())
                                    {
                                        return;
                                    }
                                }
                                else
                                {
                                    if (!CurrentFrmText.MyDoc._otherTextSign())
                                    {
                                        return;
                                    }
                                    CurrentFrmText.MyDoc.ContentChanged();
                                }
                            }
                        }
                    }
                    //获取文书XMl
                    XmlDocument tempxmldoc = new XmlDocument();
                    tempxmldoc.PreserveWhitespace = true;
                    tempxmldoc.LoadXml("<emrtextdoc/>");
                    CurrentFrmText.MyDoc.ToXML(tempxmldoc.DocumentElement);
                    bool isTakeSuperiorZz = false;
                    bool isTakeSuperiorZr = false;
                    if (CurrentFrmText.MyDoc.Us.TextKind_id == 6982569)
                    {
                        if (!pdzd(tempxmldoc.DocumentElement))
                        {
                            App.Msg("请插入诊断后提交！");
                            return;
                        }
                    }
                    if (CurrentFrmText.MyDoc.Us.TextKind_id == 126)
                    {
                        if (CurrentFrmText.MyDoc.Us.Tid == 0)
                        {
                            using (frmMessageBox messageBox = new frmMessageBox())
                            {
                                messageBox.ShowDialog();
                                if (messageBox.Succeed)
                                {
                                    isTakeSuperiorZz = messageBox.IsZZCheck;
                                    isTakeSuperiorZr = messageBox.IsZRCheck;
                                }
                            }
                        }                        
                    }
                    //修改
                    string haveSuperior = "N";
                    //(CurrentFrmText.MyDoc.HaveSuperiorSign(blfalse) ? "Y" : "N");

                    if (!CurrentFrmText.MyDoc.HaveSuperiorSign(blfalse))
                    {
                        if (btnName == "" || btnName == "btnCommit")
                        {
                            haveSuperior = "Y";
                        }
                    }
                    else
                    {
                        haveSuperior = "Y";
                    }

                    string havaTube = "N"; //(CurrentFrmText.MyDoc.HaveTubeBedSign(blfalse) ? "Y" : "N");

                    if (!CurrentFrmText.MyDoc.HaveTubeBedSign(blfalse))
                    {
                        if (btnName == "" || btnName == "btnCommit")
                        {
                            havaTube = "Y";
                        }
                    }
                    else
                    {
                        havaTube = "Y";
                    }

                    string textTitle = "";
                    string qualityTitle = "";
                    DateTime sysTime = App.wc.GetSystemTime();
                    XmlNodeList nodeList = tempxmldoc.GetElementsByTagName("div");
                    foreach (XmlNode childNode in nodeList)
                    {
                        if (childNode.Attributes["timeTitle"] != null && childNode.Attributes["timeTitle"].Value == "Y")
                        {
                            textTitle = childNode.Attributes["title"] != null ? childNode.Attributes["title"].Value : "";
                            break;
                        }
                    }
                    if (textTitle != "")
                    {
                        qualityTitle = textTitle;
                    }                  
                    if (textTitle == "" && CurrentFrmText.MyDoc.Us.RecordTime != "")
                    {
                        textTitle = CurrentFrmText.MyDoc.Us.RecordTime + "   " + CurrentFrmText.MyDoc.Us.RecordText;
                        qualityTitle = CurrentFrmText.MyDoc.Us.RecordTime + "  " + CurrentFrmText.MyDoc.Us.RecordText;
                    }
                    if (textTitle == "")
                    {
                        textTitle = App.wc.GetSystemTime().ToString("yyyy-MM-dd HH:mm") + "   " + CurrentFrmText.MyDoc.Us.TextName;
                        qualityTitle = textTitle;
                    }
                    bool haveD = false;//是否包含D型病历
                    XmlNodeList inputNodeListD = tempxmldoc.GetElementsByTagName("input");
                    foreach (XmlNode childNode in inputNodeListD)
                    {
                        if (childNode.Attributes["name"] != null)
                        {
                            string nameType = childNode.Attributes["name"].Value;
                            if (nameType == "病例分型")
                            {
                                if (childNode.InnerText.Contains("D型"))
                                {
                                    haveD = true;
                                }
                            }
                        }
                    }
                    try
                    {                         
                        qualityTitle += isTakeSuperiorZz == true ? "代主治医师查房记录" : "";
                        qualityTitle += isTakeSuperiorZr == true ? "代主任医师查房记录" : "";
                        int ttid= CurrentFrmText.MyDoc.Us.Tid;
                        int ttid2 = CurrentFrmText.MyDoc.Us.Tid;
                        int TextKind_id = CurrentFrmText.MyDoc.Us.TextKind_id;
                        bool tidflag=true;
                        //bool textkind_id=true;
                        string Role_type = App.UserAccount.CurrentSelectRole.Role_type;
                        string User_id = App.UserAccount.UserInfo.User_id;
                        bool ismore = CurrentFrmText.MyDoc.Us.IsMore;
                        int Belong_ToSys_ID=CurrentFrmText.MyDoc.Us.Belong_ToSys_ID;
                        int SickKind_ID=CurrentFrmText.MyDoc.Us.SickKind_ID;
                        string TextSuperiorSignature=CurrentFrmText.MyDoc.TextSuperiorSignature;
                        string OldTextName=CurrentFrmText.MyDoc.Us.OldTextName;
                        string SuporSign=CurrentFrmText.MyDoc.SuporSign;
                        string XmlDoc=tempxmldoc.OuterXml;

                        App.wc.SaveDoc(ref ttid2, TextKind_id, blfalse,
                                            ismore, textTitle,Role_type,User_id, patientinfo,
                                            haveSuperior, havaTube, Belong_ToSys_ID.ToString(), SickKind_ID.ToString(), OldTextName, TextSuperiorSignature, SuporSign, haveD
                                            , isTakeSuperiorZz, isTakeSuperiorZr, qualityTitle, XmlDoc);
                        if (ttid == 0)
                        {
                            //如果原来是添加的
                            CurrentFrmText.MyDoc.Us.Tid = ttid2;
                           
                        }
                        CurrentFrmText.MyDoc.Modified = false;
                        App.Msg("操作已成功！");
                        
                    }
                    catch (Exception x)
                    {
                        App.Msg("操作失败！原因："+x.Message);
                        //App.SetToolButtonByUser("ttsbtnPrint", false);//打印
                        //App.SetToolButtonByUser("ttsbtnPrintContinue", false);//续打
                    }
                    if (blfalse)
                    {
                        //InsertMeg();
                    }                   
                }
            }
            catch (Exception ex)
            {
                App.Msg(ex.Message + "|\n" + ex.TargetSite);
                //App.SetToolButtonByUser("ttsbtnPrint", false);//打印
                //App.SetToolButtonByUser("ttsbtnPrintContinue", false);//续打
            }
        }

        private static
           bool pdzd(XmlElement xml)
        {
            XmlNodeList list;
            list = xml.GetElementsByTagName("input");
            if (list != null)
            {
                if (list.Count > 0)
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        if (list[i].Attributes["name"] != null)
                        {
                            if (list[i].Attributes["name"].Value.ToString().Contains("医师签名日期"))
                            {
                                try
                                {
                                    if (list[i].Attributes["name"].InnerText != "")
                                    {
                                        return true;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    throw ex;
                                }
                            }
                        }
                    }
                }
            }
            return false;
        }


        /// <summary>
        /// 无模版的文书创建时过滤基本信息
        /// </summary>
        /// <param name="tempxmldoc"></param>
        /// <param name="inpatient"></param>
        /// <param name="TextKind_id"></param>
        /// <param name="Tid"></param>
        /// <returns></returns>
        public static XmlDocument XmlDoc(XmlDocument tempxmldoc, InPatientInfo InpatientInfo, frmText text)
        {
            //XmlDocument tempxmldoc = new XmlDocument();
            tempxmldoc.PreserveWhitespace = true;
            tempxmldoc.LoadXml("<emrtextdoc/>");
            //text.MyDoc.IsHaveDeleted = true;

            text.MyDoc.ToXML(tempxmldoc.DocumentElement);
            //text.MyDoc.IsHaveDeleted = false;

            //过滤基本信息
            try
            {
                App.wc.filterInfo(tempxmldoc.DocumentElement, InpatientInfo, text.MyDoc.Us.TextKind_id, text.MyDoc.Us.Tid);
            }
            catch (Exception ex)
            {
                string strex = ex.Message.ToString();
            }
            return tempxmldoc;
        }


        public static int GetTextWidth(Graphics g, string name, Font f)
        {
            return (int)g.MeasureString(name, f, 1000, System.Drawing.StringFormat.GenericTypographic).Width;
        }

        /// <summary>
        /// 快码查询
        /// </summary>
        /// <param name="Sql">查询语句</param>
        /// <param name="trlTepm">当前控件</param>
        /// <param name="Sel_Name"></param>
        /// <param name="Sel_Val"></param>     
        public static void FastCodeCheck(string Sql, Control trlTepm, string Sel_Name, string Sel_Val)
        {

            if (!App.CheckChineseEncode(trlTepm.Text) && !App.isHaveNumval(trlTepm.Text))
            {
                uccodeselect.IniucCodeSelect(Sql, trlTepm, Sel_Name, Sel_Val);
                trlTepm.Focus();
            }
        }


        /// <summary>
        /// 聚焦快码查询界面
        /// </summary>
        public static void SelectFastCodeCheck()
        {
            if (uccodeselect != null)
            {
                uccodeselect.Fg_Focus();
            }
        }

        /// <summary>
        /// 关闭快码查询界面
        /// </summary>
        public static void HideFastCodeCheck()
        {
            if (uccodeselect != null)
            {
                uccodeselect.Hide();                      
            }
        }




    }
}
